package pl.edu.pw.polygen.db.dao;

import java.sql.SQLException;
import java.util.List;

import org.dozer.DozerBeanMapper;
import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.stereotype.Component;

import pl.edu.pw.polygen.beans.UserBean;
import pl.edu.pw.polygen.db.dao.generic.GenericDaoImpl;
import pl.edu.pw.polygen.db.entieties.User;

@Component("userDao")
public class UserDaoImpl extends GenericDaoImpl<User, Long> implements UserDao {

	@Autowired
	private DozerBeanMapper mapper;
	
	public UserBean getUserByName(final String name) throws NullPointerException {
		
		User user = getHibernateTemplate().execute(new HibernateCallback<User>() {
			public User doInHibernate(Session session) throws HibernateException,
					SQLException {
				Criteria criteria = session.createCriteria(User.class).add(Restrictions.eq("login", name));
				List<User> users = criteria.list();
				if(users!=null && users.size()>0){
					return users.get(0);
				}else{
					throw new NullPointerException();
				}
			}
		});
		UserBean userBean = mapper.map(user,UserBean.class);
		return userBean;
	}

	
	
}
